FROM golang:1.23.4-alpine AS builder

# 使用构建参数控制是否使用国内镜像
ARG USE_CN_PROXY=false
ARG GOPROXY

# 根据参数设置 Alpine 镜像源和 Go 代理
RUN if [ "$USE_CN_PROXY" = "true" ]; then \
        echo "Using China mirrors..." && \
        sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories && \
        export GOPROXY=https://goproxy.cn,https://goproxy.io,direct && \
        export GOSUMDB=sum.golang.google.cn; \
    elif [ -n "$GOPROXY" ]; then \
        echo "Using custom proxy: $GOPROXY" && \
        export GOPROXY="$GOPROXY"; \
    else \
        echo "Using default mirrors..." && \
        export GOPROXY=https://proxy.golang.org,direct; \
    fi

ENV GO111MODULE=on

WORKDIR /app

# 先只复制依赖文件，利用 Docker 缓存
COPY go.mod go.sum ./

# 下载依赖
RUN if [ "$USE_CN_PROXY" = "true" ]; then \
        export GOPROXY=https://goproxy.cn,https://goproxy.io,direct; \
    elif [ -n "$GOPROXY" ]; then \
        export GOPROXY="$GOPROXY"; \
    fi && \
    go mod download

# 复制完整源码（包含 cmd/internal/pkg/static 等）
COPY . .

# 构建服务（使用同样的代理设置）
RUN if [ "$USE_CN_PROXY" = "true" ]; then \
        export GOPROXY=https://goproxy.cn,https://goproxy.io,direct; \
    elif [ -n "$GOPROXY" ]; then \
        export GOPROXY="$GOPROXY"; \
    fi && \
    CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags='-w -s' -o server ./cmd/server

FROM alpine:latest

# 使用构建参数控制是否使用国内镜像源
ARG USE_CN_PROXY=false

# 根据参数设置 Alpine 镜像源
RUN if [ "$USE_CN_PROXY" = "true" ]; then \
        echo "Using China mirrors for Alpine..." && \
        sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories; \
    fi && \
    apk --no-cache add ca-certificates whois bind-tools wget

WORKDIR /root/

# 复制可执行文件与静态资源
COPY --from=builder /app/server .
COPY --from=builder /app/static ./static
COPY --from=builder /app/regions.json ./
COPY --from=builder /app/api-endpoints.json ./

EXPOSE 18000
CMD ["./server"]
